<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Promise</title>
	</head>
	<body>
		
	</body>
	<script src="../js/jquery.min.js"></script>
	<script>
		/*promise 入门
		 * function timeout(ms) {
		  return new Promise((resolve, reject) => {
		    setTimeout(resolve, ms, 'done');
		  });
		}
		
		timeout(100).then((value) => {
		  console.log(value);
		});*/
		/*说明promise异步执行
		 * let promise = new Promise((resolve,reject) => {
			console.log('new promise');
			resolve();
		});
		promise.then(() => {
			console.log('promise async,resolve done!');
		});
		console.log('async:false');*/
		/*//异步加载一个图片
		var url = 'http://image.beekka.com/blog/2015/bg2015051101.jpg';
		function loadImageAsync(url){
			return new Promise((resolve,reject) => {
				const img = new Image();
				img.onload = function(){
					resolve(img);
				}
				img.onerror = function(){
					reject(new Error('Could not load image at' + url));
				}
				img.src = url;
			})
		}
		loadImageAsync(url).then((img) => {
			$('body').append(img);
			console.log('image is load success!');
		})*/
		/*//promise 实现的ajax操作的例子
		const getJSON = function(url){
			const promise = new Promise((resolve,reject) => {
				const handler = function(){
					if(this.readyState != 4){
						return ;
					}
					if(this.status === 200){
						resolve(this.response);
					}else{
						reject(this.statusText);
					}
				};
				const client = new XMLHttpRequest();
				client.open('GET',url);
				client.onreadystatechange = handler;
				client.reponseType = 'json';
				client.setRequestHeader('Accept','application/json');
				client.send();
			})
			return promise;
		}
		getJSON('../data/data.json').then((response) => {
			console.log('ajax success');
			console.log(response);
		}).then((errorData) => {
			console.log('ajax error');
			console.log(errorData);
		})*/
		//promise嵌套循环
		const p1 = new Promise((resolve,reject) => {
			setTimeout(()=> reject(new Error('fail')),1000);
		});
		const p2 = new Promise((resolve,reject) => {
			setTimeout(() => resolve(p1),1000);
		});
		//.catch函数不仅可以对p2这个promise里的错误进行捕捉，还可以对p2.then()这个回调函数里的错误进行捕捉
		//如果promise的状态已经变成resolved，再抛出错误是无效的
		//因为promise的状态一旦改变则永久保持该状态
		//promise的错误具有冒泡性质，会一直向后传递，直到被catch语句捕获，若没有catch语句对其进行捕获和处理则不会表现出任何错误形态
		p2.then(data => console.log(data)).catch(data => console.log(data));
		
		promise.then().catch().then();//对于前面发生的错误catch可以捕获并对此做出处理，catch后面的错误就不关catch的事了，除非在后面再写catch函数对其进行捕获和处理
		const p = Promise.all([p1,p2,p3]);//p1、p2、p3都是promise实例，当p1、p2、p3的状态都改变之后才会把p的状态根据他们的状态进行改变，并将p1,p2,p3的返回值当成一个数组传给p
	</script> 
</html>
